package com.ruoyi.publish.service.impl;

import java.util.Date;
import java.util.List;

import com.ruoyi.common.enums.TaskWorkFlowStaus;
import com.ruoyi.common.json.JSONObject;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.publish.domain.*;
import com.ruoyi.publish.mapper.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.publish.service.ITaskApprovalService;
import com.ruoyi.common.core.text.Convert;
import org.springframework.transaction.annotation.Transactional;

/**
 * 【请填写功能名称】Service业务层处理
 *
 * @author confusefox
 * @date 2020-12-30
 */
@Service
public class TaskApprovalServiceImpl implements ITaskApprovalService {
    @Autowired
    private TaskApprovalMapper taskApprovalMapper;

    @Autowired
    private IdReportMapper idReportMapper;

    @Autowired
    private IdAcceptRegisterMapper idAcceptRegisterMapper;

    @Autowired
    private ApprovalRecordMapper approvalRecordMapper;

    @Autowired
    private IdIdentsampleMapper idIdentsampleMapper;
    /**
     * 查询【请填写功能名称】
     *
     * @param id 【请填写功能名称】ID
     * @return 【请填写功能名称】
     */
    @Override
    public TaskApproval selectTaskApprovalById(Long id) {
        return taskApprovalMapper.selectTaskApprovalById(id);
    }

    /**
     * 查询【请填写功能名称】列表
     *
     * @param taskApproval 【请填写功能名称】
     * @return 【请填写功能名称】
     */
    @Override
    public List<TaskApproval> selectTaskApprovalList(TaskApproval taskApproval) {
        return taskApprovalMapper.selectTaskApprovalList(taskApproval);
    }

    /**
     * 新增【请填写功能名称】
     *
     * @param taskApproval 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int insertTaskApproval(TaskApproval taskApproval) {
        taskApproval.setCreateTime(DateUtils.getNowDate());
        return taskApprovalMapper.insertTaskApproval(taskApproval);
    }

    /**
     * 修改【请填写功能名称】
     *
     * @param taskApproval 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int updateTaskApproval(TaskApproval taskApproval) {
        taskApproval.setUpdateTime(DateUtils.getNowDate());
        return taskApprovalMapper.updateTaskApproval(taskApproval);
    }

    /**
     * 删除【请填写功能名称】对象
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteTaskApprovalByIds(String ids) {
        return taskApprovalMapper.deleteTaskApprovalByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除【请填写功能名称】信息
     *
     * @param id 【请填写功能名称】ID
     * @return 结果
     */
    @Override
    public int deleteTaskApprovalById(Long id) {
        return taskApprovalMapper.deleteTaskApprovalById(id);
    }


    /**
     * 新增或者更新审批人信息
     *
     * @param taskApproval
     * @return
     */
    @Transactional
    @Override
    public int addOrUpdateTask(Long loginUser,TaskApproval taskApproval) {
        int result = 0;
        String taskUserIds = "";
        if (taskApproval != null) {
            TaskApproval approvalModel = taskApprovalMapper.selectTaskApprovalByRecordIdAndLevel(taskApproval.getTaskRecordId(), taskApproval.getTaskApprovalLevel());
            if (approvalModel != null) {

                if (approvalModel.getTaskStatus() != null) {

                    if (approvalModel.getTaskStatus() == 1) {
                        // 设置审批人
                        taskUserIds = taskApproval.getTaskUserIds();
                        // 重置已经审批人
                        approvalModel.setTaskHasUserIds("");
                    } else {
                        // 获取已经添加的审批人，多人设置审批人
                        taskUserIds = approvalModel.getTaskUserIds();
                        if (StringUtils.isNotEmpty(taskUserIds)) {
                            // 追加设置审批人
                            taskUserIds = taskUserIds + taskApproval.getTaskUserIds();
                        } else {
                            // 设置审批人
                            taskUserIds = taskApproval.getTaskUserIds();
                        }
                    }
                }
                approvalModel.setTaskUserIds(taskUserIds);
                approvalModel.setUpdateTime(DateUtils.getNowDate());
                // 更新操作
                result = taskApprovalMapper.updateTaskApproval(approvalModel);
            } else {
                // 设置审核状态为待审核
                taskApproval.setTaskStatus(3);
                // 设置状态为启用状态
                taskApproval.setTaskDelete(0);
                // 设置创建时间
                taskApproval.setCreateTime(DateUtils.getNowDate());
                // 获取审批人信息
                taskUserIds = taskApproval.getTaskUserIds();
                // 插入操作
                result = taskApprovalMapper.insertTaskApproval(taskApproval);
            }
            if (result > 0) {
                IdReport report = idReportMapper.selectIdReportById(taskApproval.getTaskRecordId());

                int appLevel = taskApproval.getTaskApprovalLevel();
                // 送审级别
                switch (appLevel) {
                    // 送初审
                    case 1:
                        report.setStatus(TaskWorkFlowStaus.Stay_First.getValue().toString());
                        break;
                    // 送复审
                    case 2:
                        report.setStatus(TaskWorkFlowStaus.Stay_Again.getValue().toString());
                        break;
                    // 送终审
                    case 3:
                        report.setStatus(TaskWorkFlowStaus.Stay_End.getValue().toString());
                        break;
                }
                // 推送审核人到鉴定报告
                report.setAuditorId(taskUserIds);
                // 重置审核人
                report.setAppRemark("");
                // 待审核状态
                report.setAuditor("0");
                // 推送人
                report.setPushUser(loginUser);
                idReportMapper.updateIdReport(report);
            }
        }
        return result;
    }

    /**
     * 处理鉴定报告审批
     * 鉴定报告状态值: 见枚举类：TaskWorkFlowStaus
     *
     * @param handleUser
     * @param handleUserName
     * @param taskApproval
     * @return
     */
    @Transactional
    @Override
    public int handleTaskApproval(String handleUser, String handleUserName, TaskApproval taskApproval) {
        int result = 0;
        // 获取审批信息
        if (taskApproval != null) {
            // 鉴定报告
            IdReport report = idReportMapper.selectIdReportById(taskApproval.getTaskRecordId());
            // 审批层次
            TaskApproval approvalRecord = taskApprovalMapper.selectTaskApprovalByRecordIdAndLevel(taskApproval.getTaskRecordId(), taskApproval.getTaskApprovalLevel());
            if (report != null && approvalRecord != null) {
                // 是否有审批权限
                if (!approvalRecord.getTaskUserIds().contains(handleUser + ",")) {
                    System.out.println("此用户无审批权限!");
                    return result;
                }
                /**
                 * 鉴定报告审批日志记录信息
                 */
                ApprovalRecord recordLog = new ApprovalRecord();
                // 鉴定报告id
                recordLog.setRecordId(taskApproval.getTaskRecordId());
                // 操作人
                recordLog.setApprovalUser(Long.valueOf(handleUser));
                recordLog.setApprovalUserName(handleUserName);
                // 审批原因
                recordLog.setApprovalReason(taskApproval.getApprovalReason());

                // 获取已经审批的用户
                String taskHasUserIds = approvalRecord.getTaskHasUserIds();
                // 设置已经审批
                if (StringUtils.isNotEmpty(taskHasUserIds)) {
                    taskHasUserIds = taskHasUserIds + handleUser + ",";
                } else {
                    taskHasUserIds = handleUser + ",";
                }
                // 设置已经审批人员
                approvalRecord.setTaskHasUserIds(taskHasUserIds);
                report.setAppRemark(taskHasUserIds);

                // 获取审批状态
                switch (taskApproval.getTaskStatus()) {
                    // 审核不通过
                    case 1:
                        // 审核进度，驳回审核
                        int approvalLevel = report.getApprovalLevel();
                        if (approvalLevel == 1) {
                            // 设置初审驳回
                            report.setStatus(TaskWorkFlowStaus.Re_First.getValue().toString());
                            recordLog.setApprovalTitle(TaskWorkFlowStaus.Re_First.getStatusName());

                        } else if (approvalLevel == 2) {
                            // 设置复审驳回
                            report.setStatus(TaskWorkFlowStaus.Re_Again.getValue().toString());
                            recordLog.setApprovalTitle(TaskWorkFlowStaus.Re_Again.getStatusName());
                        } else if (approvalLevel == 3) {
                            // 设置终审驳回
                            report.setStatus(TaskWorkFlowStaus.Re_End.getValue().toString());
                            recordLog.setApprovalTitle(TaskWorkFlowStaus.Re_End.getStatusName());
                        }
                        recordLog.setSystemModule(1);
                        recordLog.setApprovalType(0);
                        recordLog.setApprovalStatus(2);
                        report.setAuditor("0");
                        approvalRecord.setTaskStatus(1);

                        // 审核不通过，获取上级审核人进行送审操作
                        TaskApproval prevTaskApproval = taskApprovalMapper.selectTaskApprovalByRecordIdAndLevel(taskApproval.getTaskRecordId(), approvalLevel - 1);
                        if (prevTaskApproval != null) {
                            // 获取审核人员
                            String userIds = prevTaskApproval.getTaskUserIds();
                            report.setAuditorId(userIds);
                            report.setAppRemark(userIds);
                        }
                        break;
                    // 审核通过
                    case 5:
                        // 证明全票通过
                        if (taskHasUserIds.equals(approvalRecord.getTaskUserIds())) {
                            // 不是终审
                            if (taskApproval.getTaskApprovalLevel() <= 2) {
                                if (taskApproval.getTaskApprovalLevel() == 1) {
                                    recordLog.setApprovalTitle(TaskWorkFlowStaus.Pass_First.getStatusName());
                                    // 初审通过
                                    report.setStatus(TaskWorkFlowStaus.Pass_First.getValue().toString());
                                } else if (taskApproval.getTaskApprovalLevel() == 2) {
                                    recordLog.setApprovalTitle(TaskWorkFlowStaus.Pass_Again.getStatusName());
                                    // 复审通过
                                    report.setStatus(TaskWorkFlowStaus.Pass_Again.getValue().toString());
                                }
                                // 设置本次环节通过
                                approvalRecord.setTaskStatus(5);
                                // 初审、复审、通过为1
                                report.setAuditor("1");
                                // 设置鉴定报告进入下级审批
                                report.setApprovalLevel(taskApproval.getTaskApprovalLevel() + 1);
                            } else {
                                // 为终审通过
                                report.setStatus(TaskWorkFlowStaus.Pass_End.getValue().toString());
                                // 关闭送审按钮
                                report.setAuditor("0");
                                recordLog.setApprovalTitle(TaskWorkFlowStaus.Pass_End.getStatusName());

                                //设置样本状态为已审核
                                String[] sampleIds = report.getSampleIds().split(",");
                                Long reId = null;
                                for (String sampleId : sampleIds) {
                                    long l = Long.parseLong(sampleId);
                                    IdIdentsample idIdentsample = idIdentsampleMapper.selectIdIdentsampleById(l);
                                    //设置样本状态
                                    idIdentsample.setStatus("2");
                                    reId=idIdentsample.getRegisterId();
                                    idIdentsampleMapper.updateIdIdentsample(idIdentsample);
                                }
                                IdAcceptRegister idAcceptRegister = idAcceptRegisterMapper.selectIdAcceptRegisterById(reId);
                                List<IdIdentsample> idIdentsamples = idIdentsampleMapper.selectIdIdentsampleByRegisterId(reId);
                                boolean status = true;
                                for (IdIdentsample idIdentsample : idIdentsamples) {
                                    String status1 = idIdentsample.getStatus();
                                    if (status1.equals("1")||status1.equals("0")||StringUtils.isEmpty(status1)){
                                        status=false;
                                        break;
                                    }
                                }
                                if (status){
                                    idAcceptRegister.setAuditStatus("6");
                                    idAcceptRegisterMapper.updateIdAcceptRegister(idAcceptRegister);
                                }

                            }
                            recordLog.setSystemModule(1);
                            recordLog.setApprovalLevel(report.getApprovalLevel());
                            recordLog.setApprovalType(0);
                            recordLog.setApprovalStatus(1);
                        }
                        break;
                    default:
                        break;
                }
                approvalRecord.setUpdateTime(DateUtils.getNowDate());
                report.setUpdateTime(DateUtils.getNowDate());
                addTaskApprovalLog(recordLog);
                // 更新鉴定报告
                result = idReportMapper.updateIdReport(report);
                // 更新审批信息
                result = taskApprovalMapper.updateTaskApproval(approvalRecord);
            }
        }
        return result;
    }

    /**
     * 审批日志记录
     */
    private void addTaskApprovalLog(ApprovalRecord recordLog) {

        // 审批时间
        recordLog.setApprovalTime(DateUtils.getNowDate());

        recordLog.setCreateTime(DateUtils.getNowDate());

        approvalRecordMapper.insertApprovalRecord(recordLog);
    }
}
